<template>
  <div class="advise-page">
    <el-header class="navbar">
      <div class="logo">思不罔学习平台</div>
      <el-menu mode="horizontal" :default-active="activeMenu">
        <el-menu-item index="1" @click="goBackHome">首页</el-menu-item>
        <el-menu-item index="2" @click="goToPersonal">个人中心</el-menu-item>
        <el-menu-item index="3" @click="goToCollection">我的收藏</el-menu-item>
      </el-menu>
      <div class="auth-buttons">
        <el-button type="text" @click="logout">退出登录</el-button>
      </div>
    </el-header>

    <el-main class="advise-content">
      <h2 class="section-title">学习建议</h2>
      <el-card shadow="hover" class="advise-card">
        <div class="advise-intro">
          <p>根据你的学习情况，通过AI为你提供个性化的学习建议。</p>
        </div>

        <!-- 建议展示区域 -->
        <div class="advice-container">
          <template v-if="adviceStatus === 'success'">
            <p class="advice-text">{{ adviceText }}</p>
          </template>
          
          <template v-else-if="adviceStatus === 'failed'">
            <el-alert type="error" show-icon>
              获取建议失败，请稍后再试
              <template #action>
                <el-button type="danger" size="small" @click="showAdvise">重试</el-button>
              </template>
            </el-alert>
          </template>
          
          <div v-if="loading" class="loading-indicator">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>思考中...</span>
          </div>
        </div>

        <el-button
            type="primary"
            @click="showAdvise"
            :disabled="loading"
            :loading="loading"
        >
          {{ hasAdvice ? '重新生成' : '获取建议' }}
        </el-button>
      </el-card>
    </el-main>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/useUserstore';
import { Loading } from '@element-plus/icons-vue';
import { ref, onUnmounted, computed } from 'vue';
import axios from '@/api/server';

const router = useRouter();
const userStore = useUserStore();

const activeMenu = ref('2');
const loading = ref(false);
const adviceText = ref('');
const adviceStatus = ref(''); // 'success' | 'failed' | ''
const adviceId = ref('');
const controller = ref(null); // 用于存储AbortController实例

// 计算属性：是否已有建议内容
const hasAdvice = computed(() => adviceText.value && adviceText.value.length > 0);

// 检查用户是否登录
const checkAuth = () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录');
    router.push('/');
    return false;
  }
  return true;
};

// 取消当前请求
const cancelRequest = () => {
  if (controller.value) {
    controller.value.abort();
    controller.value = null;
  }
};

const showAdvise = async () => {
  if (!checkAuth()) return;

  try {
    // 取消之前的请求（如果存在）
    cancelRequest();
    
    loading.value = true;
    
    // 创建新的AbortController
    controller.value = new AbortController();
    
    // 准备请求参数
    const params = {};
    if (hasAdvice.value) {
      params.retry = true; // 如果是重新生成，添加retry参数
    }
    
    // 使用axios发送请求
    const response = await axios.get('/question/getAdvice', {
      params, // 添加查询参数
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      signal: controller.value.signal // 传递取消信号
    });
    
    if (response.data.data.status === 'success') {
      adviceText.value = response.data.data.fullAdvice;
      adviceId.value = response.data.data.adviceId;
      adviceStatus.value = 'success';
      ElMessage.success('学习建议生成成功');
    } else {
      adviceStatus.value = 'failed';
      ElMessage.error('获取建议失败: ' + (response.data.data.message || '服务器错误'));
    }
  } catch (error) {
    // 如果是主动取消请求，不处理错误
    if (error.name === 'CanceledError' || error.name === 'AbortError') {
      console.log('请求被取消');
      return;
    }
    
    adviceStatus.value = 'failed';
    
    if (error.response) {
      // 处理401未授权
      if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录');
        userStore.setToken(null);
        localStorage.removeItem('token');
        router.push('/login');
        return;
      }
      ElMessage.error(`请求错误: ${error.response.data?.message || error.response.status}`);
    } else {
      ElMessage.error('网络错误: ' + error.message);
    }
  } finally {
    loading.value = false;
    controller.value = null;
  }
};

// 页面导航方法
const goBackHome = () => router.push('/home');
const goToPersonal = () => router.push('/personal');
const goToCollection = () => router.push('/collection');

// 退出登录
const logout = () => {
  userStore.setToken(null);
  localStorage.removeItem('token');
  router.push('/');
  ElMessage.success('已退出登录');
};

// 组件卸载时取消请求
onUnmounted(() => {
  cancelRequest();
});
</script>

<style scoped>
@import '../styles/Home.css';

.advice-container {
  margin: 20px 0;
  padding: 15px;
  min-height: 200px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.advice-text {
  white-space: pre-wrap;
  line-height: 1.8;
  text-align: left;
  font-size: 15px;
  width: 100%;
}

.loading-indicator {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  color: #409eff;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.8);
  padding: 5px 10px;
  border-radius: 4px;
}

.loading-indicator .el-icon {
  margin-right: 8px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.advise-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.advise-card {
  width: 80%;
  max-width: 800px;
  text-align: center;
  padding: 20px;
}

.advise-intro {
  margin-bottom: 20px;
  color: #606266;
}

.el-button {
  margin-top: 15px;
  width: 150px;
}
</style>